package com.amos.knife4j.config.exception;

import com.amos.knife4j.config.result.Result;
import com.amos.knife4j.config.result.ResultEnums;
import com.amos.knife4j.config.result.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常处理
 *
 * @author meng_lbo
 * @date 2020/2/20  13:39
 */
@ControllerAdvice
public class ExceptionHandler {

    private final static Logger log = LoggerFactory.getLogger(ExceptionHandler.class);

    /**
     * 异常处理，返回json格式的异常包装信息，而非错误页面
     *
     * @param e
     * @return
     */
    @org.springframework.web.bind.annotation.ExceptionHandler(value = Exception.class)
    @ResponseBody
    public <T> Result<T> handler(Exception e) {
        if (e instanceof BusinessException) {
            // 业务异常，响应相应错误
            BusinessException be = (BusinessException) e;
            if (be.getMessage().length() > 60) {
                log.error("参数转换异常", e);
                return ResultUtil.error(be.getCode(), "参数类型错误");
            }
            return ResultUtil.error(be.getCode(), be.getMessage());
        } else {
            log.error(" -- 特殊异常，请联系管理员 --> {}", e);
            // 系统异常，相应相应错误
            return ResultUtil.error(ResultEnums.ERROR);
        }
    }

}
